<template>
  <div class="album-details-container">
    <!-- 返回按钮 -->
    <div class="header">
      <el-button type="primary" icon="ArrowLeft" @click="goBack"
        >返回</el-button
      >
      <h1><i class="fas fa-compact-disc"></i> 专辑详情</h1>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 专辑内容 -->
    <div v-else-if="album" class="album-content">
      <!-- 专辑头部信息 -->
      <div class="album-header">
        <div class="cover-container">
          <img :src="album.cover" alt="专辑封面" class="album-cover" />
          <div class="album-actions">
            <el-button type="primary" icon="VideoPlay" @click="playAll"
              >播放全部</el-button
            >
            <el-button type="success" icon="Plus" @click="addToPlaylist"
              >添加到播放列表</el-button
            >
            <el-button type="warning" icon="Star" @click="collectAlbum"
              >收藏专辑</el-button
            >
            <el-button type="info" icon="Share" @click="shareAlbum"
              >分享专辑</el-button
            >
          </div>
        </div>

        <div class="album-info">
          <h2 class="album-title">{{ album.albumName }}</h2>

          <div class="artist-info">
            <span class="label">歌手：</span>
            <el-tag
              type="info"
              class="artist-tag"
              @click="viewArtist(album.artist.artistId)"
            >
              {{ album.artist.artistName }}
            </el-tag>
          </div>

          <div class="album-meta">
            <div class="meta-item">
              <i class="fas fa-calendar"></i>
              <span>发行日期：{{ album.releaseDate }}</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-music"></i>
              <span>流派：{{ album.genre }}</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-language"></i>
              <span>语言：{{ album.language }}</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-building"></i>
              <span>唱片公司：{{ album.recordCompany }}</span>
            </div>
            <div class="meta-item">
              <i class="fas fa-list"></i>
              <span>曲目：{{ album.trackCount }} 首</span>
            </div>
          </div>

          <!-- 已移除专辑统计数据展示 -->
        </div>
      </div>

      <!-- 歌曲列表 -->
      <div class="songs-section">
        <div class="section-header">
          <h3>
            <i class="fas fa-list-music"></i> 专辑曲目 ({{ album.trackCount }})
          </h3>
        </div>

        <el-table :data="album.songs" stripe class="songs-table">
          <el-table-column width="50" align="center">
            <template #default="{ $index }">
              <span class="song-index">{{ $index + 1 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="songName" label="歌曲标题">
            <template #default="{ row }">
              <span class="song-title" @click="playSong(row)">{{
                row.songName
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="歌手" width="180">
            <template #default>
              <span>{{ album.artist.artistName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="时长" width="100" align="right">
            <template #default="{ row }">
              <span class="song-duration">{{
                formatDuration(row.duration)
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" align="center">
            <template #default="{ row }">
              <div
                style="
                  display: flex;
                  gap: 8px;
                  justify-content: center;
                  align-items: center;
                "
              >
                <el-button
                  type="primary"
                  size="small"
                  icon="VideoPlay"
                  circle
                  @click="playSong(row)"
                />
                <el-button
                  type="success"
                  size="small"
                  icon="Plus"
                  circle
                  @click="addToPlaylist(row)"
                />
                <el-button
                  type="warning"
                  size="small"
                  icon="Star"
                  circle
                  @click="likeSong(row)"
                />
                <el-button
                  type="info"
                  size="small"
                  icon="Share"
                  circle
                  @click="shareSong(row)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 专辑描述 -->
      <div class="description-section">
        <h3><i class="fas fa-file-alt"></i> 专辑介绍</h3>
        <p class="description-content">
          {{ album.description || "暂无专辑介绍" }}
        </p>
      </div>

      <!-- 已移除专辑统计数据卡片展示 -->
    </div>

    <!-- 无数据状态 -->
    <div v-else class="no-data">
      <el-empty description="专辑信息不存在或加载失败" />
      <el-button type="primary" @click="fetchAlbumData">重新加载</el-button>
    </div>
  </div>
</template>

<script>
import {
  ElButton,
  ElCard,
  ElEmpty,
  ElMessage,
  ElMessageBox,
  ElSkeleton,
  ElTable,
  ElTableColumn,
  ElTag,
} from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import api from "../services/api";

export default {
  name: "AlbumDetails",
  components: {
    ElSkeleton,
    ElButton,
    ElTable,
    ElTableColumn,
    ElCard,
    ElTag,
    ElEmpty,
  },
  props: {
    albumId: {
      type: [Number, String],
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const album = ref(null);
    const loading = ref(true);
    const relatedAlbums = ref([]);

    // 获取专辑详情API
    const fetchAlbumData = async () => {
      loading.value = true;
      try {
        const res = await api.albumApi.getAlbumDetail(props.albumId);
        console.log("获取专辑详情成功:", res.data);
        if (res && res.code === 200 && res.data) {
          album.value = {
            albumId: res.data.albumId,
            albumName: res.data.albumName,
            cover: res.data.coverUrl,
            releaseDate: res.data.releaseDate,
            genre: res.data.genre,
            language: res.data.language,
            recordCompany: res.data.recordCompany,
            description: res.data.description,
            trackCount: res.data.trackCount,
            statistics: {
              playCount: 0,
              collectCount: 0,
              shareCount: 0,
            },
            artist: {
              artistId: res.data.artistId,
              artistName:
                res.data.artistName ||
                (res.data.artist && res.data.artist.artistName) ||
                "未知歌手",
            },
            songs: [],
          };

          // 获取专辑内的歌曲信息
          const songsRes = await api.albumApi.getAlbumSongs(props.albumId);
          console.log("获取专辑内歌曲成功:", songsRes.data);
          if (
            songsRes &&
            songsRes.code === 200 &&
            Array.isArray(songsRes.data)
          ) {
            album.value.songs = songsRes.data.map((song) => ({
              songId: song.songId,
              songName: song.songName,
              duration: song.duration,
              fileUrl: song.fileUrl,
              coverUrl: song.coverUrl,
              genre: song.genre,
              language: song.language,
              releaseDate: song.releaseDate,
              fileSize: song.fileSize,
              bitRate: song.bitRate,
              format: song.format,
            }));
          } else {
            console.warn("专辑内歌曲数据不符合预期:", songsRes);
          }
        } else {
          album.value = null;
          ElMessage.error(res?.msg || "专辑信息获取失败");
        }
      } catch (e) {
        console.error(e); // 记录错误信息
        album.value = null;
        ElMessage.error("专辑信息获取失败");
      } finally {
        loading.value = false;
      }
    };

    // 格式化数字（添加千分位）
    const formatNumber = (num) => {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };

    // 格式化时长（秒转分:秒）
    const formatDuration = (seconds) => {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
    };

    // 查看歌手详情
    const viewArtist = (artistId) => {
      ElMessage.success(`查看歌手详情: ${artistId}`);
    };

    // 播放歌曲
    const playSong = (song) => {
      ElMessage.success(`播放: ${song.songName}`);
    };

    // 添加到播放列表
    const addToPlaylist = (item) => {
      if (item.songName) {
        ElMessage.success(`已添加: ${item.songName} 到播放列表`);
      } else {
        ElMessage.success(`已添加整张专辑到播放列表`);
      }
    };

    // 播放全部
    const playAll = () => {
      ElMessage.success(`开始播放专辑: ${album.value.albumName}`);
    };

    // 收藏专辑
    const collectAlbum = () => {
      ElMessage.success(`已收藏专辑: ${album.value.albumName}`);
    };

    // 喜欢歌曲
    const likeSong = (song) => {
      ElMessage.success(`已收藏: ${song.songName}`);
    };

    // 分享歌曲
    const shareSong = (song) => {
      ElMessageBox.confirm(`分享歌曲 "${song.songName}" 给好友?`, "分享歌曲", {
        confirmButtonText: "复制链接",
        cancelButtonText: "取消",
        type: "info",
      }).then(() => {
        navigator.clipboard.writeText(
          `https://musicplatform.com/song/${song.songId}`
        );
        ElMessage.success("歌曲链接已复制到剪贴板");
      });
    };

    // 分享专辑
    const shareAlbum = () => {
      ElMessageBox.confirm(
        `分享专辑 "${album.value.albumName}" 给好友?`,
        "分享专辑",
        {
          confirmButtonText: "复制链接",
          cancelButtonText: "取消",
          type: "info",
        }
      ).then(() => {
        navigator.clipboard.writeText(
          `https://musicplatform.com/album/${album.value.albumId}`
        );
        ElMessage.success("专辑链接已复制到剪贴板");
      });
    };

    // 查看专辑
    const viewAlbum = (albumId) => {
      ElMessage.info(`查看专辑: ${albumId}`);
    };

    // 返回上一页或来源页
    const goBack = () => {
      const from = router.currentRoute.value.query.from;
      if (from) {
        router.push(from);
      } else if (window.history.length > 1) {
        router.back();
      } else {
        router.push("/");
      }
    };

    onMounted(() => {
      fetchAlbumData();
    });

    return {
      album,
      loading,
      relatedAlbums,
      formatNumber,
      formatDuration,
      viewArtist,
      playSong,
      addToPlaylist,
      playAll,
      collectAlbum,
      likeSong,
      shareSong,
      shareAlbum,
      viewAlbum,
      goBack,
    };
  },
};
</script>

<style scoped>
.album-details-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eaeaea;
}

.header h1 {
  font-size: 24px;
  color: #2c3e50;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.loading-container {
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.album-header {
  display: flex;
  gap: 30px;
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.cover-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.album-cover {
  width: 300px;
  height: 300px;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.album-actions {
  display: flex;
  gap: 15px;
}

.album-actions .el-button {
  flex: 1;
}

.album-info {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.album-title {
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 15px;
}

.artist-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  color: #666;
}

.artist-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.artist-tag:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

.album-meta {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 25px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 15px;
}

.meta-item i {
  color: #3498db;
}

.album-stats {
  display: flex;
  gap: 30px;
  margin-top: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #555;
  font-size: 15px;
}

.stat-item i {
  color: #e74c3c;
}

.songs-section {
  background: white;
  border-radius: 12px;
  padding: 25px 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.songs-table {
  width: 100%;
}

.song-index {
  color: #7f8c8d;
  font-size: 16px;
}

.song-title {
  font-weight: 500;
  color: #2c3e50;
  cursor: pointer;
  transition: color 0.2s;
}

.song-title:hover {
  color: #3498db;
}

.song-duration {
  color: #7f8c8d;
}

.description-section {
  background: white;
  border-radius: 12px;
  padding: 25px 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.description-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.description-content {
  line-height: 1.7;
  color: #555;
  text-align: justify;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 42px;
  color: #3498db;
  margin-bottom: 15px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 16px;
  color: #7f8c8d;
}

.related-section {
  background: white;
  border-radius: 12px;
  padding: 25px 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.related-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.related-albums {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 25px;
}

.album-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.album-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.album-thumb {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.album-info {
  padding: 15px;
}

.album-name {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 5px;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.album-artist {
  font-size: 14px;
  color: #7f8c8d;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-data {
  background: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

@media (max-width: 768px) {
  .album-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .album-cover {
    width: 250px;
    height: 250px;
  }

  .album-meta {
    grid-template-columns: 1fr;
  }

  .album-stats {
    flex-direction: column;
    gap: 10px;
  }

  .stats-section {
    grid-template-columns: 1fr;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
